﻿

using log4net;
using Newtonsoft.Json;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace DB
{
    /// <summary>
    /// SqlSugar 数据库操作助手类（线程安全单例模式）
    /// 
    /// 功能特点：
    /// 1. 支持多数据库类型（SQL Server, MySQL, Oracle, PostgreSQL, SQLite）
    /// 2. 支持 JSON 配置文件（config.json）管理数据库连接
    /// 3. 完整的 SQL 执行日志记录（log4net + 文本日志）
    /// 4. 慢查询监控与报警
    /// 5. 事务支持
    /// 6. 热配置重载
    /// 
    /// 使用示例：
    /// // 基本查询
    /// var users = SqlSugarHelper.Instance.Query<User>("SELECT * FROM Users");
    /// 
    /// // 事务操作
    /// SqlSugarHelper.Instance.Transaction(() => {
    ///     SqlSugarHelper.Instance.Execute("UPDATE Accounts SET Balance = Balance - 100 WHERE Id=1");
    ///     SqlSugarHelper.Instance.Execute("UPDATE Accounts SET Balance = Balance + 100 WHERE Id=2");
    /// });
    /// 
    /// // 实体操作
    /// var client = SqlSugarHelper.Instance.Entity<Product>();
    /// var newProduct = new Product { Name = "Laptop", Price = 999.99m };
    /// client.Insert(newProduct);
    /// </summary>
    public class SqlSugarHelper : IDisposable
    {
        #region 常量和字段

        /// <summary>
        /// 默认配置文件路径
        /// </summary>
        private const string DEFAULT_CONFIG_PATH = "config.json";
        /// <summary>
        /// 默认日志目录
        /// </summary>
        private const string DEFAULT_LOG_DIR = "Log4/Sqllog";
        /// <summary>
        /// 日志记录器（log4net）
        /// </summary>
        private static readonly ILog _sqlLogger = LogManager.GetLogger("SQL");
        /// <summary>
        /// 当前日志文件路径
        /// </summary>
        private static string _logPath = Path.Combine(DEFAULT_LOG_DIR, $"{DateTime.Today:yyyy-MM-dd}.log");
        /// <summary>
        /// 单例实例锁
        /// </summary>
        private static readonly object _instanceLock = new object();
        /// <summary>
        /// 单例实例
        /// </summary>
        private static SqlSugarHelper _instance;
        /// <summary>
        /// SqlSugarScope是线程安全的单例对象（推荐在WinForms中使用）
        /// </summary>
        private static SqlSugarScope _db;
        /// <summary>
        /// 资源释放标志
        /// </summary>
        private bool _disposed = false;
        /// <summary>
        /// 当前使用的数据库配置
        /// </summary>
        private DbConfig _currentConfig;

        #endregion

        /// <summary>
        /// 全局数据库访问入口
        /// </summary>
        public static SqlSugarScope Db
        {
            get
            {
                if (_db == null)
                {
                    throw new Exception("SqlSugar 未初始化！请先调用Initialize方法");
                }

                return _db;
            }
        }

        /// <summary>
        /// 初始化SqlSugar全局实例
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        public static void Initialize(string connectionString)
        {
            // 创建SqlSugarScope实例（自动管理连接池和线程安全）
            _db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = connectionString,  // 数据库连接串
                DbType = SqlSugar.DbType.SqlServer,            // 数据库类型（根据实际情况修改）
                IsAutoCloseConnection = true,         // 自动释放连接（推荐）
                InitKeyType = InitKeyType.Attribute   // 使用属性特性方式初始化主键和自增列
            },
           db =>
           {
               // 统一配置日志处理器
               db.Aop.OnLogExecuting = (sql, pars) =>
               {
                   string fullSql = GetFullSql(db, sql, pars);

                   // 记录到log4net系统
                   _sqlLogger.Debug(fullSql);
                   SetLogPath(_logPath);
                   // 记录到自定义文件
                   Log4.Info(_logPath, $"SQL执行:\n{fullSql}");
               };

               // 错误日志处理
               db.Aop.OnError = exp =>
               {
                   _sqlLogger.Error("SQL执行错误: " + exp.Message, exp);
                   Log4.Error(_logPath, $"SQL错误: {exp.Message}\n{exp.StackTrace}");
               };

               // 慢查询日志（>1秒）
               db.Aop.OnLogExecuted = (sql, pars) =>
               {
                   if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                   {
                       string fullSql = GetFullSql(db, sql, pars);
                       string msg = $"慢查询({db.Ado.SqlExecutionTime.TotalMilliseconds}ms): {fullSql}";
                       _sqlLogger.Warn(msg);
                       Log4.Warn(_logPath, msg);
                   }
               };
           });
        }
        /// <summary>
        /// 初始化SqlSugar全局实例
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        public static void Initialize(string connectionString, DbConfig config)
        {
            var dbType = GetDbType(config.DbType);
            // 创建SqlSugarScope实例（自动管理连接池和线程安全）
            _db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = connectionString,  // 数据库连接串
                DbType = SqlSugar.DbType.SqlServer,            // 数据库类型（根据实际情况修改）
                IsAutoCloseConnection = true,         // 自动释放连接（推荐）
                InitKeyType = InitKeyType.Attribute   // 使用属性特性方式初始化主键和自增列
            },
           db =>
           {
               // 统一配置日志处理器
               db.Aop.OnLogExecuting = (sql, pars) =>
               {
                   string fullSql = GetFullSql(db, sql, pars);

                   // 记录到log4net系统
                   _sqlLogger.Debug(fullSql);
                   SetLogPath(_logPath);
                   // 记录到自定义文件
                   Log4.Info(_logPath, $"SQL执行:\n{fullSql}");
               };

               // 错误日志处理
               db.Aop.OnError = exp =>
               {
                   _sqlLogger.Error("SQL执行错误: " + exp.Message, exp);
                   Log4.Error(_logPath, $"SQL错误: {exp.Message}\n{exp.StackTrace}");
               };

               // 慢查询日志（>1秒）
               db.Aop.OnLogExecuted = (sql, pars) =>
               {
                   if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                   {
                       string fullSql = GetFullSql(db, sql, pars);
                       string msg = $"慢查询({db.Ado.SqlExecutionTime.TotalMilliseconds}ms): {fullSql}";
                       _sqlLogger.Warn(msg);
                       Log4.Warn(_logPath, msg);
                   }
               };
           });
        }
        /// <summary>
        /// 初始化SqlSugar全局实例
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        public static void Initialize(string connectionString, string _dbTypes,string _isAutoCloseConnection)
        {
             
            // 创建SqlSugarScope实例（自动管理连接池和线程安全）
            _db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = connectionString,  // 数据库连接串
                DbType = GetDbType(_dbTypes),            // 数据库类型（根据实际情况修改）
                IsAutoCloseConnection = _isAutoCloseConnection.ObjToBool(),         // 自动释放连接（推荐）
                InitKeyType = InitKeyType.Attribute   // 使用属性特性方式初始化主键和自增列
            },
           db =>
           {
               // 统一配置日志处理器
               db.Aop.OnLogExecuting = (sql, pars) =>
               {
                   string fullSql = GetFullSql(db, sql, pars);

                   // 记录到log4net系统
                   _sqlLogger.Debug(fullSql);
                   SetLogPath(_logPath);
                   // 记录到自定义文件
                   Log4.Info(_logPath, $"SQL执行:\n{fullSql}");
               };

               // 错误日志处理
               db.Aop.OnError = exp =>
               {
                   _sqlLogger.Error("SQL执行错误: " + exp.Message, exp);
                   Log4.Error(_logPath, $"SQL错误: {exp.Message}\n{exp.StackTrace}");
               };

               // 慢查询日志（>1秒）
               db.Aop.OnLogExecuted = (sql, pars) =>
               {
                   if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                   {
                       string fullSql = GetFullSql(db, sql, pars);
                       string msg = $"慢查询({db.Ado.SqlExecutionTime.TotalMilliseconds}ms): {fullSql}";
                       _sqlLogger.Warn(msg);
                       Log4.Warn(_logPath, msg);
                   }
               };
           });
        }

        /// <summary>
        /// 初始化SqlSugar全局实例/初始化数据库连接
        /// </summary>
        public void InitializeDb(DbConfig config)
        {
            try
            {
                var dbType = GetDbType(config.DbType);
                var connConfig = new ConnectionConfig
                {
                    ConnectionString = config.Conn,
                    DbType = dbType,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                };

                _db = new SqlSugarScope(connConfig, ConfigureAop);

                // 验证数据库连接
                TestConnection();
            }
            catch (Exception ex)
            {
                LogError("数据库初始化失败", ex);
                throw;
            }
        }
        #region 单例访问器

        /// <summary>
        /// 获取 SqlSugarHelper 单例实例
        /// </summary>
        public static SqlSugarHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            try
                            {
                                // 优先尝试从配置文件加载
                                if (File.Exists(DEFAULT_CONFIG_PATH))
                                {
                                    LogWarning($"找到配置文件 {DEFAULT_CONFIG_PATH}，使用默认配置");
                                    _instance = new SqlSugarHelper(DEFAULT_CONFIG_PATH);
                                }
                               /* else
                                {
                                    // 使用默认配置
                                    _instance = new SqlSugarHelper(GetDefaultConfig_Test());
                                    LogWarning($"未找到配置文件 {DEFAULT_CONFIG_PATH}，使用默认配置");
                                }*/
                            }
                            catch (Exception ex)
                            {
                                LogFatal("SqlSugar 初始化失败", ex);
                                throw new ApplicationException("数据库初始化失败，请检查配置", ex);
                            }
                        }
                    }
                }
                return _instance;
            }
        }

        #endregion

        #region 构造函数和初始化

       
        /// <summary>
        /// 从 JSON 配置文件初始化
        /// </summary>
        /// <param name="jsonPath">配置文件路径</param>
        private SqlSugarHelper(string jsonPath)
        {
            ValidateConfigPath(jsonPath);
            _currentConfig = LoadConfig(jsonPath);
            InitializeDb(_currentConfig);
            LogInfo($"数据库已从配置文件初始化: {jsonPath}");
        }
       

        /// <summary>
        /// 从配置对象初始化
        /// </summary>
        /// <param name="config">数据库配置对象</param>
        private SqlSugarHelper(DbConfig config)
        {
            ValidateConfig(config);
            _currentConfig = config;
            InitializeDb(config);
            LogInfo("数据库已从内存配置初始化");
        }

        #endregion

        #region 配置处理

        /// <summary>
        /// 加载配置文件
        /// </summary>
        private DbConfig LoadConfig(string jsonPath)
        {
            try
            {
                string json = File.ReadAllText(jsonPath);
                var config = JsonConvert.DeserializeObject<DbConfig>(json);
                ValidateConfig(config);
                return config;
            }
            catch (Exception ex)
            {
                LogError($"配置文件加载失败: {jsonPath}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取默认数据库配置（开发环境使用）
        /// </summary>
        private static ConnectionConfig GetDefaultConfig()
        {
            return new ConnectionConfig
            {
                ConnectionString = @"Data Source=DESKTOP-DT8661T;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=asdfghjkl;Encrypt=False;",
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            };
        }

        /// <summary>
        /// 固定数据库
        /// </summary>
        /// <returns></returns>
        private static DbConfig GetDefaultConfig_Test()
        {
            return new DbConfig
            {
                Conn = @"Data Source=DESKTOP-DT8661T;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=asdfghjkl;Encrypt=False;",
                DbType = "SqlServer", // 注意这里修改为字符串类型以匹配DbConfig的定义
                IsAutoCloseConnection = "true",
            };
        }

        /// <summary>
        /// 验证配置文件路径有效性
        /// </summary>
        private void ValidateConfigPath(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException(nameof(path), "配置文件路径不能为空");

            if (!File.Exists(path))
                throw new FileNotFoundException($"配置文件不存在: {path}");
        }

        /// <summary>
        /// 验证数据库配置有效性
        /// </summary>
        private void ValidateConfig(DbConfig config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config), "数据库配置不能为空");

            if (string.IsNullOrWhiteSpace(config.Conn))
                throw new ArgumentException("数据库连接字符串不能为空", nameof(config.Conn));

            if (string.IsNullOrWhiteSpace(config.DbType))
                throw new ArgumentException("数据库类型不能为空", nameof(config.DbType));
        }

        #endregion

        #region 数据库初始化


        /// <summary>
        /// 配置 AOP（面向切面编程）设置
        /// </summary>
        private void ConfigureAop(SqlSugarClient db)
        {
            try
            {
                // 确保日志目录存在
                EnsureLogDirectory();

                // SQL 执行前日志记录
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    string fullSql = GetFullSql(db, sql, pars);
                    string logMessage = $"[{DateTime.Now:HH:mm:ss.fff}] SQL执行:\n{fullSql}";

                    // 记录到 log4net
                    _sqlLogger.Debug(logMessage);

                    // 记录到文本文件
                    SafeLogInfo(logMessage);
                };

                // SQL 错误处理
                db.Aop.OnError = exp =>
                {
                    string errorMessage = $"SQL执行错误: {exp.Message}\n{exp.StackTrace}";
                    _sqlLogger.Error(errorMessage, exp);
                    SafeLogError(errorMessage);
                };

                // 慢查询监控（>1秒）
                db.Aop.OnLogExecuted = (sql, pars) =>
                {
                    if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                    {
                        string fullSql = GetFullSql(db, sql, pars);
                        string slowQuery = $"慢查询({db.Ado.SqlExecutionTime.TotalMilliseconds}ms):\n{fullSql}";

                        _sqlLogger.Warn(slowQuery);
                        SafeLogWarn(slowQuery);
                    }
                };
            }
            catch (Exception ex)
            {
                _sqlLogger.Error("AOP配置失败", ex);
            }
        }

        /// <summary>
        /// 测试数据库连接是否有效
        /// </summary>
        private void TestConnection()
        {
            try
            {
                _db.Ado.ExecuteCommand("SELECT 1");
                LogInfo("数据库连接测试成功");
            }
            catch (Exception ex)
            {
                LogError("数据库连接测试失败", ex);
                throw;
            }
        }

        /// <summary>
        /// 确保日志目录存在
        /// </summary>
        private void EnsureLogDirectory()
        {
            try
            {
                var logDir = Path.GetDirectoryName(GetAbsoluteLogPath());
                if (!string.IsNullOrEmpty(logDir) && !Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                    LogInfo($"创建日志目录: {logDir}");
                }
            }
            catch (Exception ex)
            {
                _sqlLogger.Error("创建日志目录失败", ex);
            }
        }

        /// <summary>
        /// 获取绝对日志路径
        /// </summary>
        private string GetAbsoluteLogPath()
        {
            // 如果是绝对路径直接返回
            if (Path.IsPathRooted(_logPath))
                return _logPath;

            // 相对路径转换为绝对路径
            var appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            return Path.Combine(appDir, _logPath);
        }

        #endregion

        #region 数据库操作

        /// <summary>
        /// 执行 SQL 查询
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="sql">SQL 语句</param>
        /// <param name="parameters">参数对象</param>
        /// <returns>结果列表</returns>
        public List<T> Query<T>(string sql, object parameters = null) where T : class, new()
        {
            ValidateSql(sql);

            try
            {
                return _db.Ado.SqlQuery<T>(sql, parameters);
            }
            catch (Exception ex)
            {
                LogError($"SQL查询失败: {sql}", ex);
                throw;
            }
        }

        /// <summary>
        /// 执行非查询 SQL
        /// </summary>
        /// <param name="sql">SQL 语句</param>
        /// <param name="parameters">参数对象</param>
        /// <returns>受影响的行数</returns>
        public int Execute(string sql, object parameters = null)
        {
            ValidateSql(sql);

            try
            {
                return _db.Ado.ExecuteCommand(sql, parameters);
            }
            catch (Exception ex)
            {
                LogError($"SQL执行失败: {sql}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取实体操作客户端
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        public SimpleClient<T> Entity<T>() where T : class, new()
        {
            return new SimpleClient<T>(_db);
        }

         
       
        /// <summary>
        /// 使用原始 SQL 查询 State Finish
        /// </summary> 
        /// <param name="tagId"></param>
        /// <returns></returns>
        public (int State, int Finish) GetSensorStatusRawSql(string tagId)
        {
            string sql = @"
        SELECT TOP 1 State, Finish 
        FROM Tb_Sensor 
        WHERE TagID = @TagID
        ORDER BY Datetime DESC";

            // 执行原始 SQL 查询
            var result = _db.Ado.SqlQuerySingle<dynamic>(sql, new { TagID = tagId });

            if (result != null)
            {
                return (result.State, result.Finish);
            }

            return (-1, -1);
        }

        /// <summary>
        /// 执行事务操作
        /// </summary>
        /// <param name="action">事务内执行的操作</param>
        public void Transaction(Action action)
        {
            if (action == null)
                throw new ArgumentNullException(nameof(action));

            try
            {
                _db.Ado.BeginTran();
                action();
                _db.Ado.CommitTran();
            }
            catch
            {
                _db.Ado.RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 验证 SQL 语句基本有效性
        /// </summary>
        private void ValidateSql(string sql)
        {
            if (string.IsNullOrWhiteSpace(sql))
                throw new ArgumentException("SQL语句不能为空");

            if (sql.Length > 10000)
                throw new ArgumentException("SQL语句过长");
        }

        #endregion

        #region 数据库类型处理

        /// <summary>
        /// 转换数据库类型字符串
        /// </summary>
        private static SqlSugar.DbType GetDbType(string dbType)
        {
            
            if (string.IsNullOrWhiteSpace(dbType))
            {
                // 记录到自定义文件
                Log4.Info(_logPath, $"数据库类型不能为空");
                throw new ArgumentException("数据库类型不能为空");
            }

            string lowerDbType = dbType.Trim().ToLower();
            //不管传入的值是大写还是小写，又或者是驼峰等形式，全部转为小写模式
            lowerDbType = lowerDbType.ToLower();
            switch (lowerDbType)
            {
                case "sqlserver": return SqlSugar.DbType.SqlServer;
                case "mysql": return SqlSugar.DbType.MySql;
                case "oracle": return SqlSugar.DbType.Oracle;
                case "postgresql": return SqlSugar.DbType.PostgreSQL;
                case "sqlite": return SqlSugar.DbType.Sqlite;
                case "sqlite3": return SqlSugar.DbType.Sqlite;
                default:
                    // 记录到自定义文件
                    Log4.Info(_logPath, $"不支持的数据库类型: {dbType}");
                    throw new ArgumentException($"不支持的数据库类型: {dbType}");

            }
        }
        

        #endregion

        #region SQL 日志处理

        /// <summary>
        /// 获取完整 SQL 语句（带参数值）
        /// </summary>
        private static string GetFullSql(ISqlSugarClient db, string sql, SugarParameter[] pars)
        {
            try
            {
                // 优先使用 SqlSugar 内置方法
                return UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars);
            }
            catch
            {
                // 备用方案：手动格式化
                return ManualFormatSql(sql, pars);
            }
        }

        /// <summary>
        /// 手动格式化 SQL 语句
        /// </summary>
        private static string ManualFormatSql(string sql, SugarParameter[] pars)
        {
            if (pars == null || pars.Length == 0)
                return sql;

            StringBuilder fullSql = new StringBuilder(sql);
            foreach (var param in pars)
            {
                string valueStr = FormatParameterValue(param.Value);
                fullSql.Replace(param.ParameterName, valueStr);
            }
            return fullSql.ToString();
        }

        
        /// <summary>
        /// 格式化参数值为 SQL 字符串
        /// </summary>
        private static string FormatParameterValue(object value)
        {
            if (value == null) return "NULL";

            if (value is string s)
                return $"'{s.Replace("'", "''")}'";

            if (value is DateTime dt)
                return $"'{dt:yyyy-MM-dd HH:mm:ss.fff}'";

            if (value is bool b)
                return b ? "1" : "0";

            if (value is byte[] bytes)
                return $"0x{BitConverter.ToString(bytes).Replace("-", "")}";

            if (value is Guid guid)
                return $"'{guid}'";

            // 其他类型直接 ToString()
            return value.ToString();
        }
        #endregion

        #region 配置管理

        /// <summary>
        /// 设置 SQL 日志路径
        /// </summary>
        /// <param name="relativePath">相对或绝对路径</param>
        public static void SetLogPath(string relativePath)
        {
            if (string.IsNullOrWhiteSpace(relativePath))
                throw new ArgumentException("日志路径不能为空");

            _logPath = relativePath;
            LogInfo($"SQL日志路径已更新: {relativePath}");
        }

        /// <summary>
        /// 重新加载数据库配置（热更新）
        /// </summary>
        /// <param name="jsonPath">配置文件路径</param>
        public static void ReloadConfig(string jsonPath = DEFAULT_CONFIG_PATH)
        {
            lock (_instanceLock)
            {
                try
                {
                    if (_instance != null)
                    {
                        _instance.Dispose();
                        _instance = null;
                        LogInfo("释放当前数据库连接");
                    }

                    _instance = new SqlSugarHelper(jsonPath);
                    LogInfo($"数据库配置已重新加载: {jsonPath}");
                }
                catch (Exception ex)
                {
                    LogError("配置重载失败", ex);
                    throw;
                }
            }
        }

        /// <summary>
        /// 获取当前数据库配置
        /// </summary>
        public DbConfig GetCurrentConfig()
        {
            return new DbConfig
            {
                UserName = _currentConfig.UserName,
                UserID = _currentConfig.UserID,
                Conn = _currentConfig.Conn,
                DbType = _currentConfig.DbType
            };
        }

        #endregion

        #region 日志辅助方法（安全包装）

        private static void SafeLogInfo(string message)
        {
            try
            {
                Log4.Info(_logPath, message);
            }
            catch (Exception ex)
            {
                _sqlLogger.Error("文本日志记录失败", ex);
            }
        }

        private static void SafeLogWarn(string message)
        {
            try
            {
                Log4.Warn(_logPath, message);
            }
            catch (Exception ex)
            {
                _sqlLogger.Error("文本日志记录失败", ex);
            }
        }

        private static void SafeLogError(string message)
        {
            try
            {
                Log4.Error(_logPath, message);
            }
            catch (Exception ex)
            {
                _sqlLogger.Error("文本日志记录失败", ex);
            }
        }

        #endregion

        #region 静态日志方法

        private static void LogInfo(string message)
        {
            _sqlLogger.Info(message);
            SafeLogInfo(message);
        }

        private static void LogWarning(string message)
        {
            _sqlLogger.Warn(message);
            SafeLogWarn(message);
        }

        private static void LogError(string message, Exception ex = null)
        {
            _sqlLogger.Error(message, ex);
            SafeLogError($"{message}: {ex?.Message}");
        }

        private static void LogFatal(string message, Exception ex)
        {
            _sqlLogger.Fatal(message, ex);
            SafeLogError($"[FATAL] {message}: {ex.Message}");
        }

        #endregion

        #region 资源释放

        /// <summary>
        /// 释放数据库资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放数据库资源
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    try
                    {
                        _db?.Dispose();
                        LogInfo("数据库资源已释放");
                    }
                    catch (Exception ex)
                    {
                        _sqlLogger.Error("资源释放失败", ex);
                    }
                }
                _disposed = true;
            }
        }

        ~SqlSugarHelper()
        {
            Dispose(false);
        }

        #endregion
    }

    /// <summary>
    /// 数据库配置类
    /// </summary>
    public class DbConfig
    {
        /// <summary>
        /// 登录用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserID { get; set; }

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string Conn { get; set; }

        /// <summary>
        /// 数据库类型（SqlServer, MySql, Oracle, PostgreSQL, Sqlite）
        /// </summary>
        public string DbType { get; set; }
        /// <summary>
        /// /自动释放
        /// </summary>
        public string IsAutoCloseConnection { get; set; }
    }
}